/**
 * Created by yananliu on 2017/12/15.
 */
/**
 * Created by yananliu on 2017/10/1.
 */
const path = require('path');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const config = require('./package.json');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const glob = require('glob');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const webpack = require('webpack');

const entries = getEntries('src/view/**/*.tsx');

var webpackConfig =  {
    entry: entries,
    output: {
        filename: path.join(config.version,'[name].bundle.js'),
        path: path.resolve(__dirname, 'dist')
    },
    devtool: 'cheap-module-source-map',
    module: {
        loaders: [
            {test: /\.tsx$/, loader: 'awesome-typescript-loader' },
            {
                test : /\.scss$/,
                exclude : /node_modules/,
                loaders :  ExtractTextPlugin.extract({ fallback: 'style-loader', use: ['css-loader', 'sass-loader']})
            }
        ]
    },
    devServer: {
        contentBase: './',
        disableHostCheck: true,
        port : 8070,
        inline:true,
        proxy: {
            '/v1/': {
                target: 'http://139.159.216.245:8888', //测试服务器地址
                secure: false,
                changeOrigin:true
            }
        }
    },
    plugins : [
        new webpack.DefinePlugin({
            'process.env': {
                NODE_ENV: JSON.stringify('dev')
            }
        }),
        new CleanWebpackPlugin(['dist']),
        new ExtractTextPlugin(path.join(config.version,"[name].style.css"))
    ],
    resolve :{
        //这里的意思是比如index.tsx里边导包，import Hello from '../Hello'; 假如Hello扩展名是jsx 那么此时就正确的，如果是js 那么就
        //需要调整顺序让.ts在前边，那个此处的作用也就是默认的打包时候找包的扩展名
        extensions : ['.tsx','ts','.js','.json']
    },
    node: {
        fs: 'empty'
    }
};

function getEntries(globPath) {
    var files = glob.sync(globPath),
        entries = {};

    files.forEach(function(filepath) {

        filepath.match(/src\/view\/(.*)\.tsx/g);

        entries[RegExp.$1] = './' + filepath;
    });

    console.log(entries)

    return entries;
}

Object.keys(entries).forEach(function(name) {
    // 每个页面生成一个entry，如果需要HotUpdate，在这里修改entry
    //webpackConfig.entry[name] = entries[name];

    // 每个页面生成一个html
    //const nameArr = name.split('/');
    const distPath = name.replace(/\/\w+(?=\/)/,'');

    var plugin = new HtmlWebpackPlugin({
        // 生成出来的html文件名,去掉最外一层文件夹，访问url看起来顺眼一些
        filename: distPath + '.html',
        // 每个html的模版
        template: path.join(__dirname,'src/view/',(name+'.ejs')),
        // 自动将引用插入html
        inject: true,
        // 每个html引用的js模块，也可以在这里加上vendor等公用模块
        chunks: [name]
    });
    webpackConfig.plugins.push(plugin);
})

module.exports = webpackConfig;